package service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dao.Cart_dao;
import dao.Product_dao;
import dto.Pro_In_Cart;
import entity.Cart;
import entity.Product;
import service.Cart_service;

@Service
public class Cart_service_impl implements Cart_service {

	@Autowired
	private Cart_dao cart_dao;
	
	@Autowired
	private Product_dao product_dao;
	
	@Transactional
	public boolean add_ToCart(Cart cart) throws Exception {
			Integer userId=cart.getUserId();
			Integer productId=cart.getProductId();
			Cart cart_prev= cart_dao.getcartByid(userId, productId);
	try {
			if(cart_prev==null){					//若用户不存在该产品则添加
				return cart_dao.add_ToCart(cart);	
			}else{									//若用户存在该产品则更新数量
				Integer quantity=cart.getQuantity()+cart_prev.getQuantity();
				Cart cart_update=new Cart(userId,productId,quantity,cart.getChecked(),cart.getUpdateTime(),cart.getDate());
				
				return cart_dao.update_InCart(cart_update);
			}
		
		} catch (Exception e) {
			throw e;
		}
		
	}
	
	@Transactional
	public boolean remove_FromCart(Integer productId, Integer userId) throws Exception {
		// TODO Auto-generated method stub
		try {
			return cart_dao.remove_FromCart(productId, userId);
			
		} catch (Exception e) {
			throw e;
		}
	}
	
	@Transactional
	public boolean update_InCart(Cart cart) throws Exception {
		// TODO Auto-generated method stub
		try {
			return cart_dao.update_InCart(cart);
		
		} catch (Exception e) {
			throw e;
		}
	}

	public Cart getcartByid(Integer userId, Integer productId) {
		// TODO Auto-generated method stub
		return cart_dao.getcartByid(userId, productId);
	}

	
	public Pro_In_Cart get_ProInCart(Integer productId,Integer userId) {
		
		//返回具有产品原信息的dto（结合体，传输体） 
		
		Product product= product_dao.getproByid(productId);
		String pro_pic=product.getMainImage();
		String proName=product.getProName();
		String description=product.getProDescription();
		double pro_price=product.getProPrice();
		
		Cart cart= cart_dao.getcartByid(userId, productId);
		Integer quantity=cart.getQuantity();
		double pro_totalprice=pro_price*quantity;
		Integer stock=product.getStock();
		String date=cart.getDate();
		
		Pro_In_Cart pro_In_Cart =new Pro_In_Cart(productId,pro_pic,"<"+proName+">"+description,pro_price,quantity,pro_totalprice,stock,date);
		
		return pro_In_Cart;
	}

	public List<Pro_In_Cart> ProInCart_list(Integer userId) {
		 List<Cart> cartlist=cart_dao.cartlist(userId);
		 List<Pro_In_Cart> list=new ArrayList<Pro_In_Cart>();
		for (Cart cart : cartlist) {
			Integer productId= cart.getProductId();
			
			Pro_In_Cart pro_In_Cart=get_ProInCart(productId,userId);
			list.add(pro_In_Cart);
		}
		return list;
	}
	

}
